package com.handong.handserialprogram.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by userKey on 2017/7/10.
 */

public class MD5Util {

    private static final String MD5 = "MD5";
    private static final String DEFAULT_ENCODE = "UTF-8";
    /**
     * 利用MD5进行加密
     * 　　* @param str  待加密的字符串
     * 　　* @return  加密后的字符串
     * 　　* @throws NoSuchAlgorithmException  没有这种产生消息摘要的算法
     * 　　 * @throws UnsupportedEncodingException
     */
    public static String EncoderByMd5(String str) {
        //确定计算方法
        MessageDigest md5 = null;
        byte[] temp = null;
        try {
            md5 = MessageDigest.getInstance(MD5);
            md5.update(str.getBytes(DEFAULT_ENCODE));

            temp = md5.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        if (temp == null) {
            return null;
        }
        StringBuffer buffer = new StringBuffer(temp.length * 2);
        int len = temp.length;
        String hexString;
        for (int i = 0; i < len; i++) {
            hexString = Integer.toHexString(0xFF & temp[i]);
            if (hexString.length() == 1){
                buffer.append("0");
            }
            buffer.append(hexString);
        }

        return buffer.toString();
    }
}
